package com.gonsin.gview.example.data;

import com.gonsin.gview.annotations.GContext;
import com.gonsin.gview.annotations.actions.GAction;
import com.gonsin.gview.annotations.data.GDataSource;
import com.gonsin.gview.annotations.interfaces.ITableDataPicker;
import com.gonsin.base.GPageRequest;
import com.gonsin.base.GPageResult;
import com.gonsin.gview.example.bean.GroupBean;
import com.gonsin.gview.example.dao.GroupDao;
import com.gonsin.gview.example.enums.Menus;
import com.gonsin.gview.example.po.GroupSearchPo;
import com.gonsin.gview.example.utils.PageableUtils;
import com.gonsin.gview.model.menu.GViewMenu;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.gonsin.gview.annotations.interfaces.IListDataPicker;

/**
 * 查询用户组的信息
 */
@Component
public class GroupDataPicker implements ITableDataPicker<GroupBean, GroupSearchPo>, IListDataPicker<GViewMenu> {

    @Autowired private GroupDao groupDao;


    /**
     * 翻页查询用户组
     */
    @Override
    public GPageResult<GroupBean> getTableData(GContext context, String dataId, GroupSearchPo searchPo, GPageRequest pageRequest, HttpServletRequest request, Map<String, String> props) {
        Page<GroupBean> data = groupDao.findAll(PageableUtils.toPageable(pageRequest));
        return PageableUtils.toGPageResult(data);
    }

    /**
     * 添加用户组
     */
    @GAction
    public void addGroup(HttpSession session, GroupBean group){
        groupDao.saveAndFlush(group);
    }

    /**
     * 修改用户组
     */
    @GAction
    public void updateGroup(HttpSession session, GroupBean group){
        GroupBean dbGroup = groupDao.findById(group.getGroupId()).orElse(null);
        BeanUtils.copyProperties(group, dbGroup, "keyOnly", "groupId", "type");
        groupDao.saveAndFlush(dbGroup);
    }

    /**
     * 删除用户组
     */
    @GAction
    public void deleteGroup(int groupId){
        GroupBean dbGroup = groupDao.findById(groupId).orElse(null);
        groupDao.delete(dbGroup);
    }

    @Override
    public List<GViewMenu> getData(GContext context, String dataId, HttpServletRequest request, Map<String, String> props) {
        List<Menus> menus = Menus.toList();
        Collections.sort(menus, (t0, t1) -> t0.getIndex() - t1.getIndex());
        List<GViewMenu> menuBos = menus.parallelStream().map(m -> new GViewMenu(m.name(),
                m.getTitle(),
                m.getParent() == null ? null : m.getParent().name(),
                m.getUrl(),
                m.getIcon())).collect(Collectors.toList());
        return menuBos;
//        List<GroupBean> data = groupDao.findAll();
//        return data;

    }
}
